package com.leaderment.timatt.webmagic.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import com.leaderment.timatt.ApplicationInitializer;

/** 
* @author kerain
* @date 2017年11月9日
*/
public class DataStorageToLocal implements IDataStorage {

	private String filePath;
	/**
	 * 需要保存的内容
	 */
	@Override
	public String save(Date crawlDate, String fileName, String url, int page, byte[] content) {
		String absolutePath="";
		String osName = System.getProperties().getProperty("os.name");  
        if(osName.equals("Linux")){  
        	filePath=ApplicationInitializer.prop.getProperty("filePath_linux");
        }  
        else{  
        	filePath=ApplicationInitializer.prop.getProperty("filePath_window");
        }  
		FileWriter fwriter = null;
		try{
			absolutePath=filePath+fileName;
			String result=new String(content);
			fwriter = new FileWriter(filePath+fileName);
			fwriter.write(result);
		} catch (IOException ex) {
			ex.printStackTrace();
			ApplicationInitializer.log.info("文件"+fileName+"保存失败！");
		} finally {
		    try {
		    	fwriter.flush();
		    	fwriter.close();
		    } catch (IOException ex) {
		    	ex.printStackTrace();
		    	ApplicationInitializer.log.info("流关闭异常！");
		    }
		}
		return absolutePath;
	}
	
	@Override
	public String save(Date crawlDate, String fileName, String url, int page, String content) {
		String absolutePath="";
		String osName = System.getProperties().getProperty("os.name");  
        if(osName.equals("Linux")){
        	filePath=ApplicationInitializer.prop.getProperty("filePath_linux");
        }
        else{ 
        	filePath=ApplicationInitializer.prop.getProperty("filePath_window");
        }
		FileWriter fwriter = null;
		try{
			absolutePath=filePath+fileName+".html";
			File theFile = new File(absolutePath);
			File parent = theFile.getParentFile();
			if (!parent.exists())parent.mkdirs();		//创建父目录.
			if(!theFile.exists()) {
				theFile.createNewFile();
			}
			fwriter = new FileWriter(absolutePath);
			fwriter.write(content);
		} catch (IOException ex) {
			ex.printStackTrace();
			ApplicationInitializer.log.info("文件"+fileName+"保存失败！");
		} finally {
		    try {
		    	fwriter.flush();
		    	fwriter.close();
		    } catch (IOException ex) {
		    	ex.printStackTrace();
		    	ApplicationInitializer.log.info("流关闭异常！");
		    }
		}
		return absolutePath;
	}

}
